<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="等级" prop="level">
        <el-input v-model="form.level" />
      </el-form-item>
      <el-form-item label="称号" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="徽章" prop="icon">
        <VabImage
          :default-list="form.icon ? [form.icon] : []"
          :maxcount="1"
          @updateImg="updateImg"
        />
      </el-form-item>
      <el-form-item label="碳币" prop="carbon_coin">
        <el-input v-model="form.carbon_coin" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit } from '@/api/level'

  export default {
    name: 'LevelEdit',
    data() {
      return {
        form: {
          level: '',
          title: '',
          icon: '',
          carbon_coin: '',
        },
        rules: {
          level: [{ required: true, trigger: 'blur', message: '请输入等级' }],
          title: [{ required: true, trigger: 'change', message: '请输入称号' }],
          icon: [
            { required: true, trigger: 'change', message: '请选择一张图片' },
          ],
          carbon_coin: [
            { required: true, trigger: 'change', message: 'carbon_coin' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.form = Object.assign({}, row)
        }
        console.log(this.form)
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const { message } = await doEdit(this.form)
            this.$baseMessage(message, 'success')
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
      updateImg(val) {
        this.form.icon = val[0]
      },
    },
  }
</script>
